package com.gx.gxreader.base

import android.content.Context
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

abstract class BaseFragment<V, out P : BasePresenter<V>> : Fragment() {

    private lateinit var mPresenter: P

    protected var mContext: Context? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mPresenter = createPresenter()//创建Presenter
        try {
            mPresenter.attachView(this as V)
        } catch (e: Exception) {
            ClassCastException(this.toString() + "实现IPresenterView或者IPresenterView子类接口")
        }

    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(getContentViewId(), container, false)
        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initListener()
        mPresenter.start()
        initViewData()
    }

    protected abstract fun getContentViewId(): Int

    protected abstract fun createPresenter(): P

    protected abstract fun initView()

    protected abstract fun initListener()

    protected fun initViewData() {}

    protected fun showTopNavigation() {

    }

    override fun onDestroyView() {
        super.onDestroyView()
    }

    override fun onDestroy() {
        super.onDestroy()
        mPresenter.detachView()
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mContext = context
    }

    override fun onDetach() {
        super.onDetach()
        mContext = null
    }
}